<?php
/*
* The image config may have the following options:
 'image1' => array('width'           => 350,   // the maximun image width
                   'height'          => 253,   // the maximun image height
                   'constrain'       => 1,     // tells if the image does not have the maximun proportions, the Image class resize it constraining proportions
                   'fitInArea'       => true,  // tells if th image must be fitting the maximun area.
                   'quality'         => 80,    // tells the image quality 1=very low, 100=maximun quality
                   'avoidResizing'   => 1,     // Replaces the fit in area option and allows user to upload any given image respecting original dimensions.
                   'withThumb'       => true,  // Creates a thumbnail of the image
                   'thumbWidth'      => 100,   // the maximun image thumbnail width
                   'thumbHeight'     => 100,   // the maximun image thumbnail height
                   'thumbProportion' => 30,    // The reduction proportion instead of fixed the width and height
                   'thumbFitInArea'  => true); // tells if th image thumbnail must be fitting the maximun area.
*/

/**
*
* @package database
*/
class DataObjectWedWithImages extends DataObjectWed
{
    public $_imageThumbSufix = "_tumb"; // public porque se usa en transferencia de contenidos
    protected $_imageDirPath = '';
    protected $_imageUrlPath = '';
    protected $_imagesLoaded = 0;
    public $_arImages = array(); // public porque se usa en transferencia de contenidos
    protected $module;

    public function __construct()
    {
        // Images may be loaded dinamically
        $moduleName = getModuleName(get_class($this));
        if(Module::exists($moduleName))
        {
            $this->module = new Module($moduleName);
            $this->_arImages = $this->module->images[get_class($this)]? $this->module->images[get_class($this)] : $this->_arImages;
        }

        parent::__construct();
        $this->_imageDirPath   = DIR_FILE_UPLOAD ."/". $this->_dbTable;
        $this->_imageUrlPath = $GLOBALS["CONF"]["url"]["dir_file_upload"] ."/". $this->_dbTable;
    }

    public function create()
    {
        if(parent::create())
        {
            $this->loadImages($this->getID());
            return 1;
        }
        return 0;
    }

    public function get($opt=null)
    {
        if (parent::get($opt))
        {
            $this->loadImages($this->getID());
            return 1;
        }
        return 0;
    }

    // argument $opt expected in delete() is now $id: the method is extended from DataObject and $opt is NOT supported here
    public function delete($id=null)
    {
        if (parent::delete($id))
        {
            $this->deleteImages($id);
            return 1;
        }
        return 0;
    }

    public function duplicateDataOnly($id = null)
    {
        $newObj = parent::duplicate($id);
        return $newObj;
    }

    public function duplicate($id = null)
    {
        $newObj = parent::duplicate($id);
        if($newObj->getID())
        {
            $this->loadImages();
            foreach($this->_arImages as $name => $image)
            {
                if($this->imageExists($name))
                {
                    $filename = $name ."_". $newObj->getID() .".jpg";
                    copy($this->getImageDir($name), $this->_imageDirPath."/".$filename);
                }
                if($this->imageThumbExists($name))
                {
                    $filename = $name ."_". $newObj->getID() . $this->_imageThumbSufix .".jpg";
                    copy($this->getImageThumbDir($name), $this->_imageDirPath."/".$filename);
                }
            }
            return $newObj;
        }
    }

    /*
    * Image related functions
    */
    public function loadImages($id=null)
    {
        $id = $id? $id : $this->getID();
        foreach($this->_arImages AS $name => $image)
        {
            $this->_arImages[$name]['obj'] = new Image();
            $this->_arImages[$name]['obj']->filename = $name ."_". $id .".jpg";
            $this->_arImages[$name]['obj']->dirPath = $this->_imageDirPath;
            $this->_arImages[$name]['obj']->urlPath = $this->_imageUrlPath;
            $this->_arImages[$name]['obj']->load();
            if ($this->_arImages[$name]['withThumb'])
            {
                $this->_arImages[$name]['thumbObj'] = new Image();
                $this->_arImages[$name]['thumbObj']->filename = $name ."_". $id . $this->_imageThumbSufix .".jpg";
                $this->_arImages[$name]['thumbObj']->dirPath = $this->_imageDirPath;
                $this->_arImages[$name]['thumbObj']->urlPath = $this->_imageUrlPath;
                $this->_arImages[$name]['thumbObj']->load();
            }
        }
        $this->_imagesLoaded = 1;
    }

    public function printImageHTML($name, $opts=array())
    {
        if ($this->_arImages[$name]['obj']) $this->_arImages[$name]['obj']->printHTML($opts);
    }

    public function getImageHTML($name, $opts=array())
    {
        if ($this->_arImages[$name]['obj']) return $this->_arImages[$name]['obj']->getHTML($opts);
        return '';
    }

    public function printImageHTMLThumb($name, $opts=array())
    {
        if ($this->_arImages[$name]['thumbObj']) $this->_arImages[$name]['thumbObj']->printHTML($opts);
    }

    public function getImageHTMLThumb($name, $opts=array())
    {
        if ($this->_arImages[$name]['thumbObj']) return $this->_arImages[$name]['thumbObj']->getHTML($opts);
        return '';
    }

    public function updateImage($name, $filePost, $id=null)
    {
        $image = $this->_arImages[$name];
        if ($image && $filePost['name'])
        {
            $image['width'] = is_int($image['width'])? $image['width'] : (int)$image['width'];
            $image['height'] = is_int($image['height'])? $image['height'] : (int)$image['height'];
            if (!is_int($image['quality'])) $image['quality'] = 100;

            $isError = false;
            $id = $id? $id : $this->getID();
            if (!$this->_imagesLoaded) $this->loadImages($id);

            // Chequeo tipo de imagen:
            if (!$this->isValidImage($filePost)) return false;
            
            // I catch the posted file
            if ($image['obj']->catchPost($filePost)!=UPLOAD_ERR_OK)
                return $this->_error($image['obj']->getErrorMessage());
            
            // I see if the posted file is ok and a supported file format
            if (!$image['obj']->savePost())
                return $this->_error($image['obj']->getErrorMessage());

            // Saving the main image
            if($image['fitInArea'])
            {
                if (!$image['obj']->fitInArea($image['width'], $image['height'], $image['quality']))
                    return $this->_error($image['obj']->getErrorMessage());
            }
            else if(!$image['avoidResizing'])
            {
                if (!$image['obj']->resize($image['width'], $image['height'], $image['quality']))
                    return $this->_error($image['obj']->getErrorMessage());
            }
            
            // Saving Image Thumbnail
            if ($image['withThumb'])
            {
                if($image['thumbFitInArea'])
                {
                    $resizeCoef = 1;
                    if(($image['obj']->width > $image['thumbWidth']) || ($image['obj']->height > $image['thumbHeight']))
                    {
                        $resizeX = (float)$image['thumbWidth']/$image['obj']->width;
                        $resizeY = (float)$image['thumbHeight']/$image['obj']->height;
                        $resizeCoef = ($resizeX < $resizeY) ? $resizeX : $resizeY;
                    }
                    $thumbWidth = $image['obj']->width * $resizeCoef;
                    $thumbHeigth = $image['obj']->height * $resizeCoef;
                }
                else
                {
                    $thumbWidth = $image['thumbWidth'];
                    $thumbHeigth = $image['thumbHeight'];
                }

                if (!($image['thumbObj'] = $image['obj']->createThumbnail($thumbWidth, $thumbHeigth, $image['thumbObj']->filename, '', false, $image['quality'])))
                {
                    $this->_error($image['thumbObj']->getErrorMessage());
                    return 0;
                }
            }
            return 1;
        }
        return 0;
    }

    function deleteImages($doID=null)
    {
        $doID = $doID? $doID : $this->getID();
        if (!$this->_imagesLoaded)
        {
            $this->loadImages($doID);
        }
        foreach($this->_arImages AS $doImg)
        {
            $doImg['obj']->delete();
            if ($doImg['withThumb'])
            {
                $doImg['thumbObj']->delete();
            }
        }
    }

    function deleteImage($name)
    {
        if (!$this->_arImages[$name]) return 0;
        $ok = $this->_arImages[$name]['obj']->delete();
        if ($this->_arImages[$name]['withThumb'])
        {
            return $this->_arImages[$name]['thumbObj']->delete();
        }
        else return $ok;
    }

    function getImageSize($name)
    {
        if (!$this->_arImages[$name]) return 0;
        $str = $this->_arImages[$name]['width']." x ".$this->_arImages[$name]['height']." ". ($this->_arImages[$name]['fitInArea'] ? "en area" : "en tama&ntilde;o");
        if($this->_arImages[$name]['withThumb'])
        {
            $str .= "<br>thumb:<br> ".$this->_arImages[$name]['thumbWidth']."x".$this->_arImages[$name]['thumbHeight']." ". ($this->_arImages[$name]['thumbFitInArea'] ? "en area" : "en tama&ntilde;o");
        }
        return $str;
    }
    function printImageSize($name)
    {
        echo $this->getImageSize($name);
    }

    /*
    If $name is given, returns a specific image.
    Else, it returns the array of images
    */
    function getImages($name=null)
    {
        if ($name!==null)
        {
            if (!$this->_arImages[$name]) return 0;
            return $this->_arImages[$name]['obj'];
        }
        else
        {
            $images = array();
            foreach($this->_arImages AS $imageObj)
                $images[] = $imageObj;
            return $images;
        }
    }

    // Chequeos simples para evitar archivos que no sean imagenes:
    public function isValidImage($filePost)
    {
        // Chequeo dimension:
        list($w, $h, $t) = getimagesize($filePost['tmp_name']);
        if(!is_numeric($w) || !is_numeric($h)) return false;

        // Chequeo tipo (1-IMAGETYPE_GIF   2-IMAGETYPE_JPEG   3-IMAGETYPE_PNG):
        if($t!=1 && $t!=2 && $t!=3) return false;

        // Chequeo extension:
        $ext = strtolower(pathinfo($filePost['name'], PATHINFO_EXTENSION));
        if(!in_array($ext, array('gif','jpg','png'))) return false;

        return true;
    }

    public function getImageDir($name)
    {
        if ($this->imageExists($name)) return $this->_arImages[$name]['obj']->getPath();
    }

    public function getImageThumbDir($name)
    {
        if ($this->imageThumbExists($name)) return $this->_arImages[$name]['thumbObj']->getPath();
    }

    public function getImageUrl($name)
    {
        if ($this->imageExists($name)) return $this->_arImages[$name]['obj']->getUrl();
    }

    public function getImageThumbUrl($name)
    {
        if ($this->imageThumbExists($name)) return $this->_arImages[$name]['thumbObj']->getUrl();
    }

    public function imageExists($name)
    {
        if ($this->_arImages[$name]['obj'])
        {
            return $this->_arImages[$name]['obj']->exists();
        }
    }

    public function imageThumbExists($name)
    {
        if ($this->_arImages[$name]['thumbObj'])
        {
            return $this->_arImages[$name]['thumbObj']->exists();
        }
    }

    public function loadCropImage($id="", $name="")
    {
        $id = $id? $id : $this->getID();
        $this->cropImage = new Image();
        $this->cropImage->cropName = ($name!='')?$name:'ci'.$id.'.jpg';
        $this->cropImage->dirPath = $this->_imageDirPath;
        $this->cropImage->urlPath = $this->_imageUrlPath;
        return $this->cropImage;
    }

    public function getImageUrlPath()
    {
        return $this->_imageUrlPath;
    }

}

?>
